export interface User {
  id: string;
  username: string;
  password: string; // 实际项目中应该存储加密后的密码
  nickname: string;
  avatar?: string;
  createTime: number;
}

class UserModel {
  private users: User[] = [];

  async loadUsers(): Promise<void> {
    const StorageUtil = await import('../utils/StorageUtil');
    const usersData = await StorageUtil.default.get('users');
    this.users = usersData || [];
  }

  async saveUsers(): Promise<void> {
    const StorageUtil = await import('../utils/StorageUtil');
    await StorageUtil.default.set('users', this.users);
  }

  async register(username: string, password: string, nickname: string): Promise<{success: boolean; message: string}> {
    await this.loadUsers();

    // 检查用户名是否已存在
    const existingUser = this.users.find(user => user.username === username);
    if (existingUser) {
      return { success: false, message: '用户名已存在' };
    }

    // 创建新用户
    const newUser: User = {
      id: Date.now().toString(),
      username,
      password,
      nickname,
      createTime: Date.now()
    };

    this.users.push(newUser);
    await this.saveUsers();

    return { success: true, message: '注册成功' };
  }

  async login(username: string, password: string): Promise<{success: boolean; message: string; user?: User}> {
    await this.loadUsers();

    const user = this.users.find(user => user.username === username && user.password === password);
    if (user) {
      return { success: true, message: '登录成功', user };
    }

    return { success: false, message: '用户名或密码错误' };
  }

  async getUserById(id: string): Promise<User | undefined> {
    await this.loadUsers();
    return this.users.find(user => user.id === id);
  }
}

export default new UserModel();